<!-- HTML header for doxygen 1.8.3.1-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.3.1"/>
<title>AngelScript: Co-routines</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<script type="test/javascript" src="touch.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
  $(document).ready(initResizable);
  $(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
  $(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="aslogo_small.png"/></td>
  <td style="padding-left: 0.5em;">
   <div id="projectname">AngelScript
   </div>
  </td>
   <td>        <div id="MSearchBox" class="MSearchBoxInactive">
        <span class="left">
          <img id="MSearchSelect" src="search/mag_sel.png"
               onmouseover="return searchBox.OnSearchSelectShow()"
               onmouseout="return searchBox.OnSearchSelectHide()"
               alt=""/>
          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)" 
               onblur="searchBox.OnSearchFieldFocus(false)" 
               onkeyup="searchBox.OnSearchFieldChange(event)"/>
          </span><span class="right">
            <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
          </span>
        </div>
</td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.3.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
  <div id="nav-tree">
    <div id="nav-tree-contents">
      <div id="nav-sync" class="sync"></div>
    </div>
  </div>
  <div id="splitbar" style="-moz-user-select:none;" 
       class="ui-resizable-handle">
  </div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('doc_adv_coroutine.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&#160;</span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark">&#160;</span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark">&#160;</span>Macros</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(9)"><span class="SelectionMark">&#160;</span>Pages</a></div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div class="header">
  <div class="headertitle">
<div class="title">Co-routines </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p>Co-routines is a way to allow multiple execution paths in parallel, but without the hazards of pre-emptive scheduling in <a class="el" href="doc_adv_concurrent.html">multithreading</a> where one thread can be suspended at any moment so another can resume. Because co-routines always voluntarily suspend themselves in favor of the next co-routine, there is no need to worry about atomic instructions and critical sections.</p>
<p>Co-routines are not natively built-into the AngelScript library, but it can easily be implemented from the application side. In fact, the <a class="el" href="doc_addon_ctxmgr.html">Context manager</a> add-on already provides a default implementation for this.</p>
<p>To implement your own version of co-routines you will need a couple of pieces:</p>
<ul>
<li>The co-routine itself, which is just an instance of the <a class="el" href="classas_i_script_context.html">asIScriptContext</a> object. Each co-routine will have its own context object that holds the callstack of the co-routine.</li>
<li>A function that will permit the script to create, or spawn, new co-routines. This function will need to be able to refer to starting function of the new co-routine. This reference can be done by name, or perhaps more elegantly with a <a class="el" href="doc_datatypes_funcptr.html">function pointer</a>. Once invoked this function will instanciate the new context, and prepare it with the starting function.</li>
<li>A function that will permit a co-routine to yield control to the next co-routine. This function will simply suspend the current context so the next co-routine can be resumed.</li>
<li>A simple control algorithm for the co-routines. This can just be a loop that will iterate over an array of co-routines, i.e. contexts, until all of them have finished executing. When a new co-routine is created it is simply appended to the array to be picked up when the current co-routine yields the control.</li>
</ul>
<p>A simple implementation of the function that spawns a new co-routine may look like this:</p>
<div class="fragment"><div class="line"><span class="keywordtype">void</span> CreateCoRoutine(<span class="keywordtype">string</span> &amp;func)</div>
<div class="line">{</div>
<div class="line">  <a class="code" href="classas_i_script_context.html" title="The interface to the virtual machine.">asIScriptContext</a> *ctx = <a class="code" href="angelscript_8h.html#ad3a20dc58093b92a5a44c7b6ada34a10" title="Returns the currently active context.">asGetActiveContext</a>();</div>
<div class="line">  <span class="keywordflow">if</span>( ctx )</div>
<div class="line">  {</div>
<div class="line">    <a class="code" href="classas_i_script_engine.html" title="The engine interface.">asIScriptEngine</a> *engine = ctx-&gt;<a class="code" href="classas_i_script_context.html#a07f12016c5435aec5b63449abb6e4d8d" title="Returns a pointer to the engine.">GetEngine</a>();</div>
<div class="line">    <span class="keywordtype">string</span> mod = ctx-&gt;<a class="code" href="classas_i_script_context.html#a1c101300447f2909e5d188409a7180f6" title="Returns the function at the specified callstack level.">GetFunction</a>()-&gt;<a class="code" href="classas_i_script_function.html#af03c30e4764f81c01400d7f77a8d0832" title="Returns the name of the module where the function was implemented.">GetModuleName</a>();</div>
<div class="line"></div>
<div class="line">    <span class="comment">// We need to find the function that will be created as the co-routine</span></div>
<div class="line">    <span class="keywordtype">string</span> decl = <span class="stringliteral">&quot;void &quot;</span> + func + <span class="stringliteral">&quot;()&quot;</span>; </div>
<div class="line">    <a class="code" href="classas_i_script_function.html" title="The interface for a script function description.">asIScriptFunction</a> *funcPtr = engine-&gt;<a class="code" href="classas_i_script_engine.html#a9f7cdc52b59034e6e55eb8a56b427aa4" title="Return an interface pointer to the module.">GetModule</a>(mod.c_str())-&gt;GetFunctionByDecl(decl.c_str());</div>
<div class="line">    <span class="keywordflow">if</span>( funcPtr == 0 )</div>
<div class="line">    {</div>
<div class="line">      <span class="comment">// No function could be found, raise an exception</span></div>
<div class="line">      ctx-&gt;<a class="code" href="classas_i_script_context.html#a4ed608208cafdebe5676df079e27d392" title="Sets an exception, which aborts the execution.">SetException</a>((<span class="stringliteral">&quot;Function &#39;&quot;</span> + decl + <span class="stringliteral">&quot;&#39; doesn&#39;t exist&quot;</span>).c_str());</div>
<div class="line">      <span class="keywordflow">return</span>;</div>
<div class="line">    }</div>
<div class="line"></div>
<div class="line">    <span class="comment">// Create a new context for the co-routine</span></div>
<div class="line">    <a class="code" href="classas_i_script_context.html" title="The interface to the virtual machine.">asIScriptContext</a> *coctx = engine-&gt;<a class="code" href="classas_i_script_engine.html#a2630e1cd03ffab0fee9b820bf0afe42a" title="Creates a new script context.">CreateContext</a>();</div>
<div class="line">    coctx-&gt;<a class="code" href="classas_i_script_context.html#a43976f42dfc6c1af23e132d36265173a" title="Prepares the context for execution of the function.">Prepare</a>(funcPtr);</div>
<div class="line"></div>
<div class="line">    <span class="comment">// Add the new co-routine context to the array of co-routines</span></div>
<div class="line">    coroutines.push_back(coctx);</div>
<div class="line">  }</div>
<div class="line">}</div>
</div><!-- fragment --><p>The yield function is even simpler:</p>
<div class="fragment"><div class="line"><span class="keywordtype">void</span> Yield()</div>
<div class="line">{</div>
<div class="line">  <a class="code" href="classas_i_script_context.html" title="The interface to the virtual machine.">asIScriptContext</a> *ctx = <a class="code" href="angelscript_8h.html#ad3a20dc58093b92a5a44c7b6ada34a10" title="Returns the currently active context.">asGetActiveContext</a>();</div>
<div class="line">  <span class="keywordflow">if</span>( ctx )</div>
<div class="line">  { </div>
<div class="line">    <span class="comment">// Suspend the context so the next co-routine can be resumed</span></div>
<div class="line">    ctx-&gt;<a class="code" href="classas_i_script_context.html#ad4ac8be3586c46069b5870e40c86544a" title="Suspends the execution, which can then be resumed by calling Execute again.">Suspend</a>();</div>
<div class="line">  }</div>
<div class="line">}</div>
</div><!-- fragment --><p>A basic control algorithm might look like this:</p>
<div class="fragment"><div class="line">std::vector&lt;asIScriptContext *&gt; coroutines;</div>
<div class="line"><span class="keywordtype">void</span> Execute()</div>
<div class="line">{</div>
<div class="line">  <span class="keywordtype">int</span> n = 0;</div>
<div class="line">  <span class="keywordflow">while</span>( coroutines.size() &gt; 0 )</div>
<div class="line">  {</div>
<div class="line">    <span class="comment">// Resume the co-routine</span></div>
<div class="line">    <span class="keywordtype">int</span> r = coroutines[n]-&gt;Execute();</div>
<div class="line">    <span class="keywordflow">if</span>( r == <a class="code" href="angelscript_8h.html#a867f14b4137dd4602fda1e616b217a69a7b5644be315c46f2fa44f032731242c7" title="The execution is suspended and can be resumed.">asEXECUTION_SUSPENDED</a> )</div>
<div class="line">    {</div>
<div class="line">      <span class="comment">// Resume the next co-routine</span></div>
<div class="line">      <span class="keywordflow">if</span>( ++n == coroutines.size() )</div>
<div class="line">        n = 0;</div>
<div class="line">    }</div>
<div class="line">    <span class="keywordflow">else</span></div>
<div class="line">    {</div>
<div class="line">      <span class="comment">// The co-routine finished so let&#39;s remove it</span></div>
<div class="line">      coroutines[n]-&gt;Release();</div>
<div class="line">      coroutines.erase(n);</div>
<div class="line">    }</div>
<div class="line">  }</div>
<div class="line">}</div>
</div><!-- fragment --><dl class="section see"><dt>See Also</dt><dd><a class="el" href="doc_addon_ctxmgr.html">Context manager</a>, <a class="el" href="doc_samples_corout.html">Co-routines</a>, <a class="el" href="doc_adv_concurrent.html">Concurrent scripts</a> </dd></dl>
</div></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
  <ul>
    <li class="footer">Generated on Sun Dec 18 2016 12:35:27 for AngelScript by
    <a href="http://www.doxygen.org/index.html">
    <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.3.1 </li>
  </ul>
</div>
</body>
</html>
